﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HyEduOnline.Server.Common;
using HyEduOnline.Entities;
using HyEduOnline.Server.Student;
using HyEudOnline.Server.Common;

namespace WebSite.Areas.WebApi.Controllers
{
    public class StudentMangerController : StudentsController
    {
        //
        // GET: /Api/StudentManger/
        private StudentsDAO studentsDAO = new StudentsDAO();

        /// <summary>
        /// POST api/StudentManger/PostStu
        ///新增item数据，
        /// </summary>
        /// <param name="item">item,新增数据</param>
        public int PostStu(TbStudents item)
        {
            if (!string.IsNullOrEmpty(item.SPassWord))
            {
                item.SPassWord = Utitil.MD5(item.SPassWord);//密码加密
            }
            if (ModelState.IsValid)
            {
                studentsDAO.Insert(item);
                return 1;//新增数据成功
            }
            else
            {
                //数据验证失败
                return 0;
            }


        }


        /// <summary>
        /// PUT api/StudentManger/PutStu/5,更新数据
        /// </summary>
        public int PutStu(int id, TbStudents item)
        {
            if (id != item.Id)
            {
                //数据无效
                return -1;
            }

            try
            {
                if (!string.IsNullOrEmpty(item.SPassWord))//更新密码
                {
                    item.SPassWord = Utitil.MD5(item.SPassWord);//MD5加密密码
                    studentsDAO.Update(item);
                }
                else
                {//不更新密码
                    TbStudents newItem = studentsDAO.GetByID(id);
                    item.SPassWord = newItem.SPassWord;
                    studentsDAO.Update(item);
                }              
            }
            catch (Exception ex)
            {
                //更新数据失败
                return -2;
            }

            //更新成功
            return 1;


        }

        /// <summary>
        /// GET api/Students/Get/id
        ///返回指定id的数据
        /// </summary>
        /// <param name="id">id,主键</param>
        public JsonResult GetStu(int id)
        {
            TbStudents item = studentsDAO.GetByID(id);

            //置空密码字段，不发送到客户端
            TbStudents stuItem = new TbStudents();
            ClassValueCopier.Copy(stuItem, item);
            stuItem.SPassWord = "";

            return Json(stuItem, JsonRequestBehavior.AllowGet);
        }

    }
}
